package com.ruoyi.wx.config;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.google.common.collect.Maps;
import com.ruoyi.wx.domain.WxApp;
import com.ruoyi.wx.service.IWxAppService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;

/**
 * 微信小程序配置
 * @author jerry
 *
 */
@Configuration
public class WxMaConfiguration {
	
	private static Map<String, WxMaService> maServices = Maps.newHashMap();
	
	public static Map<String, WxMaService> getMaServices() {
        return maServices;
    }
	
	@Autowired
	private IWxAppService wxAppService;
	
	@PostConstruct
    public void initServices() {
        final List<WxApp> configs = wxAppService.list();
        if (configs == null) {
            throw new RuntimeException("没有配置小程序信息！");
        }
        
        maServices = configs.stream().map(a -> {
        	WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
        	config.setAppid(a.getAppId());
        	config.setSecret(a.getAppSecret());

            WxMaService service = new WxMaServiceImpl();
            service.setWxMaConfig(config);
            return service;
        }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a, (o, n) -> o));
    }
	
	@Bean
	public WxPayService wxPayService() {
		WxPayService wxPayService = new WxPayServiceImpl();
		return wxPayService;
	}
	
}
